<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <div class="header-actions">
        <el-button @click="refreshUsers" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card mb-3">
      <el-form :model="filterForm" inline>
        <el-form-item label="用户类型">
          <el-select v-model="filterForm.role" placeholder="全部类型" clearable>
            <el-option label="学生" value="STUDENT" />
            <el-option label="商家" value="MERCHANT" />
            <el-option label="配送员" value="DELIVERY" />
            <el-option label="管理员" value="ADMIN" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-select v-model="filterForm.enabled" placeholder="全部状态" clearable>
            <el-option label="正常" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="搜索">
          <el-input 
            v-model="filterForm.keyword" 
            placeholder="输入用户名或手机号" 
            clearable 
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table 
        :data="users" 
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="100" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" width="150" show-overflow-tooltip />
        <el-table-column prop="role" label="用户类型" width="100">
          <template #default="scope">
            <el-tag :type="getRoleType(scope.row.role)">
              {{ getRoleText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.enabled ? 'success' : 'danger'">
              {{ scope.row.enabled ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.enabled"
              type="warning"
              size="small"
              @click="toggleUserStatus(scope.row, false)"
            >
              禁用
            </el-button>
            <el-button
              v-else
              type="success"
              size="small"
              @click="toggleUserStatus(scope.row, true)"
            >
              启用
            </el-button>
            <el-button
              size="small"
              @click="viewUserDetail(scope.row)"
            >
              查看
            </el-button>
            <el-popconfirm
              title="确认删除该用户？"
              @confirm="deleteUserConfirm(scope.row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  :disabled="scope.row.role === 'ADMIN'"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="用户详情"
      width="600px"
    >
      <div v-if="selectedUser" class="user-detail">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-item">
            <span class="label">用户ID：</span>
            <span>{{ selectedUser.id }}</span>
          </div>
          <div class="detail-item">
            <span class="label">用户名：</span>
            <span>{{ selectedUser.username }}</span>
          </div>
          <div class="detail-item">
            <span class="label">真实姓名：</span>
            <span>{{ selectedUser.realName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">手机号：</span>
            <span>{{ selectedUser.phone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">邮箱：</span>
            <span>{{ selectedUser.email || '未设置' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">用户类型：</span>
            <el-tag :type="getRoleType(selectedUser.role)">
              {{ getRoleText(selectedUser.role) }}
            </el-tag>
          </div>
          <div class="detail-item">
            <span class="label">状态：</span>
            <el-tag :type="selectedUser.enabled ? 'success' : 'danger'">
              {{ selectedUser.enabled ? '正常' : '禁用' }}
            </el-tag>
          </div>
          <div class="detail-item">
            <span class="label">注册时间：</span>
            <span>{{ formatTime(selectedUser.createTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">最后更新：</span>
            <span>{{ formatTime(selectedUser.updateTime) }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getUsers, updateUserStatus, deleteUser } from '../../api/admin'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const users = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const detailVisible = ref(false)
const selectedUser = ref(null)

// 筛选条件
const filterForm = reactive({
  role: '',
  enabled: null,
  keyword: ''
})

// 获取用户列表
const getUsers = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      role: filterForm.role || undefined,
      enabled: filterForm.enabled,
      keyword: filterForm.keyword || undefined
    }
    
    // 模拟数据 - 实际中这里应该调用API
    const mockUsers = [
      {
        id: 1,
        username: 'admin',
        realName: '系统管理员',
        phone: '13800000000',
        email: 'admin@campus.com',
        role: 'ADMIN',
        enabled: true,
        createTime: '2024-01-01 00:00:00',
        updateTime: '2024-12-24 10:30:00'
      },
      {
        id: 2,
        username: 'student1',
        realName: '张三',
        phone: '13800000001',
        email: 'zhangsan@student.com',
        role: 'STUDENT',
        enabled: true,
        createTime: '2024-01-15 09:20:00',
        updateTime: '2024-12-20 14:15:00'
      },
      {
        id: 3,
        username: 'student2',
        realName: '李四',
        phone: '13800000002',
        email: 'lisi@student.com',
        role: 'STUDENT',
        enabled: true,
        createTime: '2024-01-18 16:45:00',
        updateTime: '2024-12-22 11:30:00'
      },
      {
        id: 4,
        username: 'merchant1',
        realName: '王老板',
        phone: '13800000003',
        email: 'wang@merchant.com',
        role: 'MERCHANT',
        enabled: true,
        createTime: '2024-02-01 10:00:00',
        updateTime: '2024-12-23 15:20:00'
      },
      {
        id: 5,
        username: 'delivery1',
        realName: '赵师傅',
        phone: '13800000005',
        email: 'zhao@delivery.com',
        role: 'DELIVERY',
        enabled: true,
        createTime: '2024-02-10 14:30:00',
        updateTime: '2024-12-24 09:45:00'
      },
      {
        id: 6,
        username: 'student3',
        realName: '钱七',
        phone: '13800000006',
        email: '',
        role: 'STUDENT',
        enabled: false,
        createTime: '2024-03-01 11:15:00',
        updateTime: '2024-12-20 16:30:00'
      }
    ]
    
    // 筛选数据
    let filteredUsers = mockUsers
    if (filterForm.role) {
      filteredUsers = filteredUsers.filter(user => user.role === filterForm.role)
    }
    if (filterForm.enabled !== null) {
      filteredUsers = filteredUsers.filter(user => user.enabled === filterForm.enabled)
    }
    if (filterForm.keyword) {
      filteredUsers = filteredUsers.filter(user => 
        user.username.includes(filterForm.keyword) || 
        user.realName.includes(filterForm.keyword) || 
        user.phone.includes(filterForm.keyword)
      )
    }
    
    total.value = filteredUsers.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    users.value = filteredUsers.slice(start, end)
    
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新用户列表
const refreshUsers = () => {
  currentPage.value = 1
  getUsers()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getUsers()
}

// 重置
const handleReset = () => {
  filterForm.role = ''
  filterForm.enabled = null
  filterForm.keyword = ''
  currentPage.value = 1
  getUsers()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getUsers()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  getUsers()
}

// 获取角色类型
const getRoleType = (role) => {
  const typeMap = {
    'ADMIN': 'danger',
    'STUDENT': 'primary',
    'MERCHANT': 'success',
    'DELIVERY': 'warning'
  }
  return typeMap[role] || 'info'
}

// 获取角色文本
const getRoleText = (role) => {
  const textMap = {
    'ADMIN': '管理员',
    'STUDENT': '学生',
    'MERCHANT': '商家',
    'DELIVERY': '配送员'
  }
  return textMap[role] || '未知'
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 切换用户状态
const toggleUserStatus = async (user, enabled) => {
  try {
    const action = enabled ? '启用' : '禁用'
    await ElMessageBox.confirm(
      `确认${action}用户 "${user.realName}" ？`,
      `${action}用户`,
      {
        confirmButtonText: `确认${action}`,
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API
    // await updateUserStatus(user.id, enabled)
    
    // 模拟成功
    user.enabled = enabled
    user.updateTime = new Date().toISOString()
    ElMessage.success(`${action}成功`)
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 查看用户详情
const viewUserDetail = (user) => {
  selectedUser.value = user
  detailVisible.value = true
}

// 删除用户
const deleteUserConfirm = async (userId) => {
  try {
    // 这里应该调用API
    // await deleteUser(userId)
    
    // 模拟删除
    const index = users.value.findIndex(user => user.id === userId)
    if (index > -1) {
      users.value.splice(index, 1)
      total.value--
    }
    
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 页面初始化
onMounted(() => {
  getUsers()
})
</script>

<style scoped>
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.user-detail {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: var(--text-primary);
  border-bottom: 1px solid var(--border-light);
  padding-bottom: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
}

.detail-item .label {
  color: var(--text-regular);
  font-weight: 500;
  min-width: 100px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .el-form--inline .el-form-item {
    display: block;
    margin-bottom: 12px;
  }
}
</style>
